//
//  WBUserAccoutViewModel.swift
//  weiboD
//
//  Created by gao2015 on 2016/12/5.
//  Copyright © 2016年 gao2015. All rights reserved.
//

import UIKit

class WBUserAccoutViewModel: NSObject {
    //单例的全局访问点
    static let shareUserAccout : WBUserAccoutViewModel = WBUserAccoutViewModel()
    //在这个viewModel中提供一个userAccount属性,在创建这个viewModel的时候创建
    var userAccount : WBUserAccount?{
        //每次创建这个viewModel对象的时候都有一个userAccount生成,提供从沙盒中加载的数据
        return WBUserAccount.loadUserAccount()
    }
    //access_token属性用来判断access_token是否过期
    var access_token : String?{
        guard let token = userAccount?.access_token else{
            return nil
        }
        if userAccount?.expireDate?.compare(Date()) == ComparisonResult.orderedDescending{
            //没过期
            return token
        }else{
            return nil
        }
    }
    
    
    //提供一个方法获取accessToken
    func requestAcessToken(code:String, callBack:@escaping (Bool)-> ()) {
        //这里的error为啥没类型
        WBNetworkTool.shareTool.requestAccessToken(code: code, callBack: {(respose:Any?, error) -> () in
            
            if error != nil{
                print("出错了！！！！！！！")
                callBack(false)
            }
//            print(respose)
            //字典转模型
            let dict = respose as![String : Any]
            let userCount = WBUserAccount(dic: dict)
            //给用户信息赋值
            self.getUserinfo(userAccount: userCount, callBack: callBack )
        })
    }
    
    //MARK:提供方法获取userInfo
    func getUserinfo(userAccount:WBUserAccount, callBack:@escaping (Bool)-> ()){
        let uid = userAccount.uid
        let access_token = userAccount.access_token
        //response这里是any的话有问题?
        WBNetworkTool.shareTool.requestGetUserInfo(accessToken: access_token!, uid: uid, callBack: {(response, error) -> () in
            if error != nil{
                //                print(error)
                return
            }
            //            print(response)
            //字典转模型
            let dict = response as! [String:Any]
            userAccount.name = dict["name"] as? String
            userAccount.avatar_large = dict["avatar_large"] as? String
            //将用户信息归档
            userAccount.saveUserAccount()
            callBack(true)
        })
    }
}
